package com.common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.framework.model.impl.DataMap;

/**
 * 导出工具类
 * @author wangpc
 *
 */
public class ExportUtil {

	
	public static void exportCsv(HttpServletResponse response, String[] headers, String[] keys,List<DataMap> dataList, String filename){
		
		response.setContentType("application/vnd.ms-excel");
		
        PrintWriter writer = null;
		try {
			filename = URLEncoder.encode(filename, "UTF-8");
			response.addHeader("Content-Disposition",
			            "attachment;filename=" + filename+DateUtil.getVersionSequence() + ".csv");
			        response.setHeader("cache-control", "public");
			        response.setHeader("Pragma", "public");
			        
			        response.setCharacterEncoding("GBK");
			        writer = response.getWriter();
			        
		            //获取列表遍历数据
			        if(headers!=null && headers.length>0){
						
						for (String header : headers)
				        {
				            writer.print(header);
				            writer.print(",");
				            writer.print("\t");
				        }
						writer.print("\n");
					}
					
					if(dataList!=null && dataList.size()>0){
						
						for (DataMap dataMap1 : dataList) {
					      	
							for(String key : keys){
								
								writer.print(dataMap1.get(key));
					            writer.print(",");
					            writer.print("\t");
							}
							
							writer.print("\n");
							
					    }
						
					}
			        
		            writer.flush();
		            
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(writer!=null){
				writer.close();
			}
		}
		
	}
	
}
